/**
 * CollectionTaskDetailPage
 * 采集任务详情页面
 * Features: 实时进度、详细信息、失败表列表、操作按钮
 */

import React from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { Card, Descriptions, Button, Space, Tag, Empty } from 'antd'
import { ArrowLeftOutlined, PauseCircleOutlined, RedoOutlined } from '@ant-design/icons'
import TaskProgressBar from '@/components/collection/TaskProgressBar'
import { useCollectionTaskPolling, useCancelCollectionTask, useRetryFailedTables } from '@/hooks/useCollectionTask'
import { TaskStatus, TaskType } from '@/services/models/types'

const STATUS_TAG_CONFIG: Record<TaskStatus, { color: string; text: string }> = {
  [TaskStatus.PENDING]: { color: 'default', text: '等待中' },
  [TaskStatus.RUNNING]: { color: 'processing', text: '运行中' },
  [TaskStatus.SUCCESS]: { color: 'success', text: '成功' },
  [TaskStatus.FAILED]: { color: 'error', text: '失败' },
  [TaskStatus.CANCELLED]: { color: 'default', text: '已取消' },
  [TaskStatus.PARTIAL_SUCCESS]: { color: 'warning', text: '部分成功' },
}

export const CollectionTaskDetailPage: React.FC = () => {
  const { id } = useParams<{ id: string }>()
  const navigate = useNavigate()

  // 任务详情 (带轮询)
  const { data: task, isLoading } = useCollectionTaskPolling(Number(id))

  // 取消任务
  const cancelMutation = useCancelCollectionTask()

  // 重试失败的表
  const retryMutation = useRetryFailedTables()

  const handleCancel = async () => {
    if (!task) return
    await cancelMutation.mutateAsync(task.id)
  }

  const handleRetry = async () => {
    if (!task) return
    await retryMutation.mutateAsync(task.id)
  }

  if (isLoading) {
    return <div className="p-6">加载中...</div>
  }

  if (!task) {
    return (
      <div className="p-6">
        <Empty description="任务不存在" />
        <Button onClick={() => navigate('/collection')} className="mt-4">
          返回列表
        </Button>
      </div>
    )
  }

  const statusConfig = STATUS_TAG_CONFIG[task.status]

  return (
    <div className="p-6">
      <div className="mb-4 flex justify-between items-center">
        <Space>
          <Button icon={<ArrowLeftOutlined />} onClick={() => navigate('/collection')}>
            返回
          </Button>
          <h1 className="text-2xl font-bold">采集任务详情 - #{task.id}</h1>
        </Space>

        <Space>
          {task.status === TaskStatus.RUNNING && (
            <Button
              danger
              icon={<PauseCircleOutlined />}
              onClick={handleCancel}
              loading={cancelMutation.isPending}
            >
              取消任务
            </Button>
          )}

          {task.status === TaskStatus.PARTIAL_SUCCESS && task.failedTables && task.failedTables.length > 0 && (
            <Button
              type="primary"
              icon={<RedoOutlined />}
              onClick={handleRetry}
              loading={retryMutation.isPending}
            >
              重试失败的表
            </Button>
          )}
        </Space>
      </div>

      <Space direction="vertical" size="large" className="w-full">
        {/* 进度条 */}
        <TaskProgressBar task={task} />

        {/* 任务信息 */}
        <Card title="任务信息">
          <Descriptions column={2} bordered>
            <Descriptions.Item label="任务ID">{task.id}</Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag color={statusConfig.color}>{statusConfig.text}</Tag>
            </Descriptions.Item>

            <Descriptions.Item label="数据源">{task.datasourceName}</Descriptions.Item>
            <Descriptions.Item label="采集类型">
              <Tag color={task.type === TaskType.FULL ? 'blue' : 'cyan'}>
                {task.type === TaskType.FULL ? '全量' : '增量'}
              </Tag>
            </Descriptions.Item>

            <Descriptions.Item label="开始时间">{task.startTime || '-'}</Descriptions.Item>
            <Descriptions.Item label="结束时间">{task.endTime || '-'}</Descriptions.Item>

            <Descriptions.Item label="总表数">{task.totalTables}</Descriptions.Item>
            <Descriptions.Item label="成功/失败">
              <span className="text-green-600">{task.completedTables}</span> /
              <span className="text-red-600 ml-1">{task.failedTables?.length || 0}</span>
            </Descriptions.Item>

          </Descriptions>
        </Card>

        {/* 失败表列表 */}
        {task.failedTables && task.failedTables.length > 0 && (
          <Card title={`失败的表 (${task.failedTables.length})`}>
            <div className="grid grid-cols-3 gap-2">
              {task.failedTables.map((failedTable, index) => (
                <Tag key={index} color="red" title={failedTable.failureReason}>
                  {failedTable.schemaName ? `${failedTable.schemaName}.${failedTable.tableName}` : failedTable.tableName}
                </Tag>
              ))}
            </div>
          </Card>
        )}
      </Space>
    </div>
  )
}

export default CollectionTaskDetailPage
